<template>
  <el-card style="width: 40%; height: 95%; margin-top: 20px;">
    <div
      style="display: flex;flex-direction: row; align-items: center; justify-content: space-between; flex-wrap: nowrap; margin-bottom: 50px;">
      <span style="font-weight: bold; margin-left: 20px; font-size: large;">个人用户信息</span>
      <el-button type="warning" size="small" style="margin-right: 20px;" @click="exit = 2">更改个人信息</el-button>
    </div>
    <div style="display: flex; flex-direction: column; align-items: flex-start; flex-wrap: nowrap; height: auto;">
      <div style="margin-bottom: 20px; margin-left: 60px;">
        <span class="label-span"><i class="el-icon-user"></i> 用户名：</span>
        <span class="text-span">{{ userInfo.userName }}</span>
      </div>
      <div style="margin-bottom: 20px; margin-left: 60px;">
        <span class="label-span"><i class=" el-icon-mobile"></i> 电话号码：</span>
        <span class="text-span">{{ userInfo.userAccount }}</span>
      </div>
      <div style="margin-bottom: 20px; margin-left: 60px;">
        <span class="label-span"><i class=" el-icon-message"></i> 邮箱：</span>
        <span class="text-span">{{ userInfo.userEmail }}</span>
      </div>

      <el-button type="primary" style="width: 60%; margin-left: 105px;" size="mini" plain
        @click="exit = 1">修改密码</el-button>
      <el-collapse-transition>
        <img v-if="this.exit === 0" style="width: 200px; height: 200px; margin-left: 160px;"
          src="../../../assets/img/404.png" alt="图片加载失败" />
        <div v-if="this.exit === 1"
          style="margin-top: 30px; width: 100%; display: flex; display: flex; flex-direction: column;">
          <el-form style="width: auto;" :model="updatePassword" :rules="rulesPassword" ref="updatePassword"
            label-width="82px">
            <el-form-item label="密码:" class="regist-item" prop="userPassword">
              <el-input type="password" show-password v-model="updatePassword.userPassword" autocomplete="off"
                style="width: 200px;"></el-input>
            </el-form-item>

            <el-form-item label="确认密码:" class="regist-item" prop="checkPassword">
              <el-input type="password" show-password v-model="updatePassword.checkPassword" autocomplete="off"
                style="width: 200px;"></el-input>
            </el-form-item>
          </el-form>
          <div style="display: flex; flex-wrap: nowrap; justify-content: center;">
            <el-button type="primary" size="mini" plain :loading="passwordLoading" @click="setUpdatePassword">{{ passwordLoading ? '修改中...'
              : '确认' }}</el-button>
            <el-button type="info" size="mini" plain @click="cancelChangePassword">取消</el-button>
          </div>
        </div>
        <div v-if="this.exit === 2"
          style="margin-top: 30px; width: 100%; display: flex; display: flex; flex-direction: column;">
          <el-form style="width: auto;" :model="updateUserInfo" :rules="rulesUserInfo" ref="updateUserInfo"
            label-width="82px">
            <el-form-item label="用户名:" class="regist-item" prop="userName">
              <el-input v-model="updateUserInfo.userName" autocomplete="off" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="电话号码:" class="regist-item" prop="userAccount">
              <el-input v-model="updateUserInfo.userAccount" autocomplete="off" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="邮箱:" class="regist-item" prop="userEmail">
              <el-input v-model="updateUserInfo.userEmail" autocomplete="off" style="width: 200px;"></el-input>
            </el-form-item>
          </el-form>
          <div style="display: flex; flex-wrap: nowrap; justify-content: center;">
            <el-button type="primary" size="mini" plain :loading="updateLoading" @click="setUpdateUsetInfo">{{ updateLoading ? '修改中...'
              : '确认' }}</el-button>
            <el-button type="info" size="mini" plain @click="cancelChangeUserInfo">取消</el-button>
          </div>
        </div>
      </el-collapse-transition>
    </div>
  </el-card>
</template>

<script>
import { toast } from '../../../composables/util'
export default {
  name: "Account",
  data() {
    // 俩次密码输入校验
    var validatePass = (rule, value, callback) => {
      if (value !== this.updatePassword.userPassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      userInfo: '',
      exit: 0,
      // 更新用户信息
      updateLoading: false,
      updateUserInfo: {
        userAccount: '',
        userName: '',
        userEmail: ''
      },
      rulesUserInfo: {
        userAccount: [
          { required: true, message: '请输入账户', trigger: 'blur' },
          { min: 11, max: 11, message: '账号应为11位', trigger: ['blur', 'change'] }
        ],
        userName: [
          { required: true, message: '请输入名字', trigger: 'blur' },
          { min: 0, max: 10, message: '名字不超过10位', trigger: ['blur', 'change'] }
        ],
        userEmail: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]
      },
      // 更新用户密码
      passwordLoading: false,
      updatePassword: {
        userPassword: '',
        checkPassword: ''
      },
      rulesPassword: {
        userPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 8, max: 16, message: '密码应为8-15位', trigger: ['blur', 'change'] }
        ],
        checkPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validatePass, trigger: ['blur', 'change'] }
        ],
      },
    }
  },
  methods: {
    // 修改密码
    setUpdatePassword() {
      this.$refs['updatePassword'].validate((valid) => {
        if (valid) {
          this.passwordLoading = true
          setTimeout(() => {
            this.putPassword()
          }, 1000)
        }else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    putPassword() {
      const user = {
        id: this.userInfo.id,
        // userAccount: '',
        // userEmail:'',
        // userName:'',
        userPassword: this.updatePassword.userPassword
      }
      console.log(user);
      this.request.put("/user/updateUser",user).then(
        response => {
          if (response.data.code === 1) {
            toast("修改密码成功,请重新登录！", this)
            this.exitLogin()
          } else {
            toast("修改密码失败,请稍后重试", this, "error")
          }
        },
        error => {
          console.log(error.message)
        }
      ).finally(() => {
        this.passwordLoading = false
      })
    },
    exitLogin() {
      sessionStorage.clear()
      this.$router.push("/login")
    },
    cancelChangePassword() {
      this.exit = 0
      this.resetForm('updatePassword')
    },
    // 修改账户信息
    cancelChangeUserInfo() {
      this.exit = 0
      this.updateUserInfo.userAccount = this.userInfo.userAccount
      this.updateUserInfo.userName = this.userInfo.userName
      this.updateUserInfo.userEmail = this.userInfo.userEmail
    },
    setUpdateUsetInfo() {
      this.$refs['updateUserInfo'].validate((valid) => {
        if (valid) {
          this.updateLoading = true
          setTimeout(() => {
            this.putUsetInfo()
          }, 1000)
        }else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    putUsetInfo() {
      const user = {
        id: this.userInfo.id,
        userAccount: this.updateUserInfo.userAccount,
        userEmail: this.updateUserInfo.userEmail,
        userName: this.updateUserInfo.userName
      }
      console.log(user);
      this.request.put("/user/updateUser",user).then(
        response => {
          if (response.data.code === 1) {
            this.$message({
              message: "修改账户信息成功！",
              type: 'success'
            });
            sessionStorage.setItem('login_user', JSON.stringify(user))
            this.userInfo = JSON.parse(sessionStorage.getItem('login_user'))
            this.$router.go(0)
          } else {
            this.$message({
              message: "修改账户信息成功失败,请稍后重试！",
              type: 'success'
            });
          }
        },
        error => {
          console.log(error.message)
        }
      ).finally(() => {
        this.updateLoading = false
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  created() {
    this.userInfo = JSON.parse(sessionStorage.getItem('login_user'))
    // this.updateUserInfo = this.userInfo
    this.updateUserInfo.userAccount = this.userInfo.userAccount
    this.updateUserInfo.userName = this.userInfo.userName
    this.updateUserInfo.userEmail = this.userInfo.userEmail
  },
  computed: {
  }
}

</script>

<style scoped>
.label-span {
  margin-left: 90px;
  font-size: medium;
  color: #93c5fd;
}

.text-span {
  font-weight: bold;
}

::v-deep .el-form-item {
  margin-left: 130px;
}
</style>